import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class FileDeal {
    private File inFile;
    private String unionLines;
    private boolean inString;
    private boolean inComment;

    public FileDeal(File inFile) {
        this.inFile = inFile;
        this.unionLines = "";
        this.inString = false;
        this.inComment = false;
    }

    public void readFile() throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(inFile));

        String line;
        while ((line = br.readLine()) != null) {
            line = delComment(line);
            line += '\n';
            unionLines += line;
        }
    }

    public String getUnionLines() {
        return unionLines;
    }


    public String splicing(String line, int begin, int end) {
        String left = line.substring(0, begin);
        String right = line.substring(end + 1, line.length());
        line = left + " " + right;
        return line;
    }

    //去除注释
    public String delComment(String line) {
        int commentBegin = 0;
        int commentEnd = line.length();

        for (int i = 0; i < line.length(); i++) {
            if (line.charAt(i) == '/' && i != line.length() - 1 && line.charAt(i + 1) == '/') {
                if (!inComment && !inString) {
                    if (i == 0) {
                        line = "";
                    } else {
                        line = line.substring(0, i);
                    }
                    break;
                }
            } else if (line.charAt(i) == '/' && i != line.length() - 1 && line.charAt(i + 1) == '*') {
                if (!inComment && !inString) {
                    inComment = true;
                    commentBegin = i;
                    i++;
                }
            } else if (line.charAt(i) == '*' && i != line.length() - 1 && line.charAt(i + 1) == '/') {
                if (inComment && !inString) {
                    inComment = false;
                    commentEnd = i + 1;
                    line = splicing(line, commentBegin, commentEnd);
                    i = commentBegin;
                }
            } else if (line.charAt(i) == '"') {
                if (!inComment && !inString) {
                    inString = true;
                } else if (!inComment && inString) {
                    inString = false;
                }
            }
        }

        if (inComment) {
            line = line.substring(0, commentBegin);
        }

        return line;
    }
}
